package com.holly.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.holly.pojo.PageResultData;
import com.holly.pojo.Result;
import com.holly.pojo.Student;
import com.holly.pojo.StudentQueryParam;
import com.holly.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author holly
 * @create 2025-07-03 13:43
 */
@RequestMapping("/students")
@Slf4j
@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping
    public Result page(StudentQueryParam param){
        log.info("分页查询所有学生信息，参数：{}",param);
        PageResultData<Student> pageResultData = studentService.page(param);
        return Result.success(pageResultData);
    }

    @PostMapping
    public Result save(@RequestBody Student student){
        log.info("保存学生信息，参数：{}",student);
        studentService.save(student);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getInfoById(@PathVariable Integer id){
        log.info("查询学生信息，参数：{}",id);
        Student student = studentService.getById(id);

        return Result.success(student);
        // 方案1：使用Jackson动态过滤（推荐）去除clazzName属性
//        ObjectMapper mapper = new ObjectMapper();
//        mapper.setFilterProvider(new SimpleFilterProvider()
//                .addFilter("studentFilter",
//                        SimpleBeanPropertyFilter.serializeAllExcept("clazzName")));
//        return Result.success(mapper.valueToTree(student)); // 返回JsonNode
//        // 1. 将对象转为 Map
//        ObjectMapper mapper = new ObjectMapper();
//        Map<String, Object> dataMap = mapper.convertValue(student, Map.class); // student 是原有数据对象
//
//        // 2. 移除不需要的字段
//        dataMap.remove("clazzName"); // 动态删除指定字段
//
//        // 3. 构建返回结果
//        return Result.success(dataMap);

    }

    @PutMapping
    public Result update(@RequestBody Student student){
        log.info("更新学生信息，参数：{}",student);
        studentService.update(student);
        return Result.success();
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        log.info("删除学生信息，参数：{}",ids);
        studentService.delete(ids);
        return Result.success();
    }

    @PutMapping("/violation/{id}/{score}")
    public Result updateViolation(@PathVariable Integer id, @PathVariable String score){
        log.info("添加学生违规信息，参数：id={},score={}",id,score);
        if("null".equals(score) || "".equals(score) || score == null){
            score = "0";
        }
        Integer scoreNum  = Integer.parseInt(score);
        log.info("添加学生违规信息，参数：id={},score={}",id,scoreNum);
        studentService.updateViolation(id,scoreNum);
        return Result.success();
    }



}
